//
//  EFANotSelPjtVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/9/1.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFANotSelPjtVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "EFAPjtSelPjtTCell.h"
#import "EFAModel.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"

@interface EFANotSelPjtVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *sureBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *cancelBarBtnItem;
@property (strong, nonatomic) EFAProjectModel *pjtModel;
@property (assign, nonatomic) int pageSize;
@end

static NSString *const kReuseCellId = @"EFAPjtSelPjtTCell";
//static NSInteger const kRequestSize = 20;

@implementation EFANotSelPjtVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _pageSize = 1;
    [self initNavigationBar];
    [self initSubViews];
}

//- (BOOL)hidesBottomBarWhenPushed {
//    return self.viewType == EFAPjtManagerVCTypeManager;
//}

- (void)initNavigationBar {
    self.navigationItem.title = @"选择项目";
    self.navigationItem.leftBarButtonItem = self.cancelBarBtnItem;
    self.navigationItem.rightBarButtonItem = self.sureBarBtnItem;
    [self.sureBarBtnItem setEnabled:NO];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
//    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有项目" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"global_empty"];
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.pjtModel.project_list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFAPjtSelPjtTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    [cell configViewWithPjtListItem:self.pjtModel.project_list[indexPath.row]];
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 14.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row < self.pjtModel.project_list.count) {
        EFAPjtListItem *item = self.pjtModel.project_list[indexPath.row];
        item.isSelected = !item.isSelected;
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    
    [self.sureBarBtnItem setEnabled:self.pjtModel.hasSelPjt];
    if (self.pjtModel.hasSelPjt && self.isSingleSelected) {
        [self sureBarBtnTapped:self.sureBarBtnItem];
    }
}

#pragma mark - event response
- (void)cancelBarBtnTapped:(UIBarButtonItem *)item {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)sureBarBtnTapped:(UIBarButtonItem *)item {
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.successHandle) {
            self.successHandle(self.pjtModel.selPjtArray);
            self.successHandle = nil;
        }
    }];
}
#pragma mark - private methods
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.pjtModel.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    self.tableView.mj_footer.hidden = self.pjtModel.totalZero;
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestPjtListWithHeader:isHeader];
}

//- (EFAProjectModel *)deviceModelWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
//    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
//        return self.pjtModel;
//    }
//    
//    EFAProjectModel *temp = [EFAProjectModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
//    if (!temp) {
//        return self.pjtModel;
//    }
//    
//    if (AddMore && self.pjtModel) {
//        [self.pjtModel addMoreWithData:temp];
//    } else {
//        self.pjtModel = temp;
//    }
//    return self.pjtModel;
//}

#pragma mark - network request
- (void)requestPjtListWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        [self tableViewEndRefresh:isHeader];
        return;
    }
    //    NSInteger startIndex = isHeader ? 0 : self.userList.user_list.count;
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"page" : @(_pageSize),
                           @"size" : @"20",
                           @"regeo_info":@"",
                           @"keyword":@""
                           };
    
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiProjectList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求项目列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        self.pjtModel = [EFAProjectModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求项目列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)cancelBarBtnItem {
    if (!_cancelBarBtnItem) {
        _cancelBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnTapped:)];
//        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
//                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
//        [_cancelBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
//        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
//                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
//        [_cancelBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _cancelBarBtnItem;
}
- (UIBarButtonItem *)sureBarBtnItem {
    if (!_sureBarBtnItem) {
        _sureBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sureBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_sureBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_sureBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _sureBarBtnItem;
}
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
//        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
